package cn.gson.crm.model.service;

import cn.gson.crm.model.dao.CustomerDao;
import cn.gson.crm.model.dao.EmployeeDao;
import cn.gson.crm.model.dao.LinkManDao;
import cn.gson.crm.model.dao.SalesDao;
import cn.gson.crm.model.mapper.CustomerMapper;
import cn.gson.crm.model.pojos.*;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Transactional(rollbackFor = Exception.class)
public class CustomerService {

    @Autowired
    CustomerDao customerDao;

    @Autowired
    LinkManDao linkManDao;

    @Autowired
    CustomerMapper customerMapper;

    @Autowired
    EmployeeDao employeeDao;

    //customer查询所有
    public List<Customer> all(String source,String name,String type){
        Customer customer = new Customer();
        customer.setCustomerSource(source);
        customer.setCustomerName(name);
        customer.setCustomerType(type);
        return customerMapper.select(customer);
    }

    //中国地图
    public List<Customer> mapCustomer(){
        return customerMapper.mapCustomer();
    }

    //customer删除：把客户修改为失效客户
    public int delete(String customerDele,int customerId){
        return customerMapper.updateDelete(customerDele, customerId);
    }

    //customer查询出所有的负责人
    public List<Employee> selectEmp(int ygId){
        return customerMapper.selectEmp(ygId);
    }

    //customer查询出所有的负责人
    public List<Employee> selectEmpCustomer(int ygId){
        return customerMapper.selectEmpCustomer(ygId);
    }

    //cusUpdate:客户信息查询所有:yg_id不为空
    public List<Customer> SelectUpdate(int ygId,String dele,String name,String type){
        List<Customer> customers = customerMapper.selectUpdate(ygId,dele, name, type);
        for (int i = 0; i < customers.size(); i++) {
            List<Contract> contracts = customerMapper.timesContract((int) customers.get(i).getCustomerId(), 0);
            if(contracts.size()>0){
                customers.get(i).setCustomerDele("签约客户");
                if(contracts.size()>=2){
                    customers.get(i).setCustomerDele("重复购买");
                }
            }
            customerDao.save(customers.get(i));
        }
        return customers;
    }

    //cusUpdate:客户新增或修改
    public void addUpdate(Customer customer){
        customerDao.save(customer);
    }

    //customerUpdate删除客户
    public String deleteCustomer(int customerId){
        String result = "success";
        List<Contract> contracts = customerMapper.timesContract(customerId, 0);
        if(contracts.size()>0){
            result="fail";
        }else{
            customerMapper.updateDelete("失效客户", customerId);
        }
        return result;
    }

    //detailed:根据客户id查询联系人
    //linkman:根据客户/负责人/联系人查询联系人
    public List<Linkman> selectLinkman(int ygId,int customerId,String linkName){
        return customerMapper.selectLinkman(ygId,customerId,linkName);
    }

    //detailed:根据客户id查询负责人
    public List<Customer> selectYname(int customerId){
        return customerMapper.selectYname(customerId);
    }

    //linkman:新增修改
    public void addLink(Linkman linkman){
        linkManDao.save(linkman);
    }

    //linkman:删除联系人
    public String deleteLink(int linkId){
        String result="success";
        Linkman linkman = customerMapper.linkmanContract(linkId);
        List<Contract> contract = linkman.getContract();
        if(contract.size()<0){
            result="fail";
        }else{
            customerMapper.deleteLink(linkId);
        }
        return result;
    }

    //meger:根据负责人id或者客户名称或者客户名称字母
    public List<Customer> selectMeger(int ygId,String customerName){
        return customerMapper.selectMeger(ygId,customerName);
    }

    //时间线：销售机会
    public List<Sales> timesSales(int customerId){
        return customerMapper.timesSales(customerId);
    }

    //时间线：跟进记录
    public List<Follow> timesFollow(int customerId,int followId){
        return customerMapper.timesFollow(customerId,followId);
    }

    //时间线：订单
    public List<Order> timesOrder(int customerId,int orderId){
        List<Order> orders = customerMapper.timesOrder(customerId, orderId);
        for (int i = 0; i < orders.size(); i++) {
            if(orders.get(i).getOrderCharge()!=null){
                Employee employee = customerMapper.selectem(orders.get(i).getOrderCharge());
                orders.get(i).setEmployee(employee);
            }
            if(orders.get(i).getEreApprover()!=null){
//                Employee employee2 = customerMapper.selectem(orders.get(i).getEreApprover());
//                orders.get(i).setEmployee2(employee2);
            }
        }
        return orders;
    }

    //时间线：合同
    public List<Contract> timesContract(int customerId,int contractId){
        List<Contract> contracts = customerMapper.timesContract(customerId, contractId);
        for (int i = 0; i < contracts.size(); i++) {
            if(contracts.get(i).getOursigner()!=null){
                Employee employee = customerMapper.selectem(contracts.get(i).getOursigner().intValue());
                contracts.get(i).setEmployee(employee);
            }
            if(contracts.get(i).getCrApprover()!=null){
                Employee employee2 = customerMapper.selectem(contracts.get(i).getCrApprover().intValue());
                contracts.get(i).setEmployee2(employee2);
            }
        }
        return contracts;
    }

    //时间线：回款计划
    public List<MoneyBackPlan> timesMoney(int customerId,int backId){
        return customerMapper.timesMoney(customerId,backId);
    }

    //时间线：回款记录
    public List<RefundRecord> timesRefund(int customerId,int refundId){
        return customerMapper.timesRefund(customerId,refundId);
    }

    //时间线：退货
    public List<ReturnGoods> timesReturn(int customerId,int returnId){
        List<ReturnGoods> returnGoods = customerMapper.timesReturn(customerId, returnId);
        for (int i = 0; i < returnGoods.size(); i++) {
            if(returnGoods.get(i).getReturnChager()!=null){
                Employee employee = customerMapper.selectem(returnGoods.get(i).getReturnChager().intValue());
                returnGoods.get(i).setEmployee(employee);
            }
            if(returnGoods.get(i).getEreApprover()!=null){
                Employee employee2 = customerMapper.selectem(returnGoods.get(i).getEreApprover().intValue());
                returnGoods.get(i).setEmployee2(employee2);
            }
        }
        return returnGoods;
    }

    //时间线：换货
    public List<ExchangeGoods> timesExchange(int customerId,int excId){
        List<ExchangeGoods> exchangeGoods = customerMapper.timesExchange(customerId, excId);
        for (int i = 0; i < exchangeGoods.size(); i++) {
            if(exchangeGoods.get(i).getExcCharge()!=null){
                Employee employee = customerMapper.selectem(exchangeGoods.get(i).getExcCharge().intValue());
                exchangeGoods.get(i).setEmployee(employee);
            }
            if(exchangeGoods.get(i).getEreApprover()!=null){
                Employee employee2 = customerMapper.selectem(exchangeGoods.get(i).getEreApprover().intValue());
                exchangeGoods.get(i).setEmployee2(employee2);
            }
        }
        return exchangeGoods;
    }

    //时间线：交付计划
    public List<DeliveryPlan> timesPlan(int customerId,int planId){
        return customerMapper.timesPlan(customerId,planId);
    }

    //时间线：竞争对手
    public List<Competitor> timesCompetitor(int customerId,int comId){
        return customerMapper.timesCompetitor(customerId,comId);
    }

    //时间线：报价
    public List<Offer> timesOffer(int customerId,int offerId){
        return customerMapper.timesOffer(customerId,offerId);
    }

    //时间线：解决方案
    public List<Solution> timesSolution(int customerId,int solutionId){
        return customerMapper.timesSolution(customerId,solutionId);
    }

    //时间线：维修工单
    public List<RepairOrder> timesRepair(int customerId,int repairId){
        return customerMapper.timesRepair(customerId,repairId);
    };

    //时间线：客户投诉
    public List<Complaints> timesComplaints(int customerId,int comId){
        return customerMapper.timesComplaints(customerId,comId);
    };

    //时间线：客户服务
    public List<cn.gson.crm.model.pojos.CustomerService> timesService(int customerId,int cusId){
        return customerMapper.timesService(customerId,cusId);
    };

    //时间线：所有
    public List<Times> timeAll(int customerId){
        List<Times> map = customerMapper.timesAll(customerId);
        return map;
    }

    //时间线：退换货
    public List<Times> timesGoods(int customerId){
        return customerMapper.timesGoods(customerId);
    }

    //时间线：退换货
    public List<Times> timesMoneyAll(int customerId){
        return customerMapper.timesMoneyAll(customerId);
    }

    //客户导入
    public Map<String,Object> importCustomer(String customer) throws ParseException {
        JSONObject object = (JSONObject) JSONObject.parse(customer);
        List list = object.getObject("customer",List.class);
        JSONArray array = (JSONArray) JSONArray.parseArray(String.valueOf(list));
        //查询所有的客户
        List<Customer> all = (List<Customer>)customerDao.findAll();
        JSONObject jsonObject =null;
        //判断客户名称与数据库是否有重复值
        List<Integer> cusName = new ArrayList<>();
        //判断导入的数据中是否有重复的客户名称
        List<String> cusNameList = new ArrayList<>();
        //判断导入的数据是否有两条或多条重复的数据
        List<String> repetition = new ArrayList<>();
        //判断导入的电话号码是否正确
        List<String> phoneList = new ArrayList<>();
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
        //判断客户来源
        List<String> sourceList = new ArrayList<>();
        //判断客户类型
        List<String> typeList = new ArrayList<>();
        //判断日期格式
        List<String> dateList = new ArrayList<>();
        //收集要返回的验证
        Map<String,Object> map = new HashMap<>();
        for (int i = 0; i < array.size(); i++) {
            jsonObject = (JSONObject)array.get(i);
            //获取传过来的客户名称
            String name = jsonObject.getString("customerName");

            //判断客户名称与数据库是否有重复值
            for (int j = 0; j < all.size(); j++) {
                if(name.equals(all.get(j).getCustomerName())){
                    cusName.add(i+1);
                }
            }

            //判断导入的数据中是否有重复的客户名称
            JSONObject jsonObject1=null;
            for (int i1 = 0; i1 < array.size(); i1++) {
                jsonObject1 = (JSONObject)array.get(i1);
                if(i!=i1){
                    if(!jsonObject.getString("customerName").equals("重复值")){
                        if(name.equals(jsonObject1.getString("customerName"))){
                            cusNameList.add(name);
                        }
                    }
                }
            }

            //判断电话号码是否正确
            if(!jsonObject.getString("customerName").equals("重复值")){
                if(jsonObject.getString("customerPhone").length()!=11){
                    phoneList.add(i+1+"");
                }
                Pattern p = Pattern.compile(regex);
                boolean customerPhone = p.matcher(jsonObject.getString("customerPhone")).matches();
                if(!customerPhone){
                    phoneList.add(i+1+"");
                }
            }

            //判断客户来源
            System.out.println(jsonObject);
            if(!jsonObject.getString("customerName").equals("重复值")){
                if(!jsonObject.getString("customerSource").equals("社交获客") && !jsonObject.getString("customerSource").equals("网络获客")
                        && !jsonObject.getString("customerSource").equals("电话来访") && !jsonObject.getString("customerSource").equals("客户介绍")
                        && !jsonObject.getString("customerSource").equals("媒体宣传")
                ){
                    sourceList.add(i+1+"");
                }
            }

            //判断客户类型
            if(!jsonObject.getString("customerName").equals("重复值")){
                if(!jsonObject.getString("customerType").equals("公司") && !jsonObject.getString("customerType").equals("个人")){
                    typeList.add(i+1+"");
                }
            }

            //判断日期格式
            if(!jsonObject.getString("customerName").equals("重复值")){
                if(!jsonObject.getString("customerDate").equals("非法日期格式")){
                    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                    Date date = formatter.parse(jsonObject.getString("customerDate"));
                    System.err.println("riqi:"+jsonObject.getString("customerDate"));
                    if(jsonObject.getString("customerDate")==null){
                        System.out.println(1);
                        dateList.add(i+1+"");
                    }
                    if(!jsonObject.getString("customerDate").equals(formatter.format(date))){
                        System.out.println(2);
                        dateList.add(i+1+"");
                    }
                }else{
                    dateList.add(i+1+"");
                }
            }
        }

        for (int i = 0; i < array.size(); i++) {
            jsonObject = (JSONObject)array.get(i);
            //判断导入的数据是否有两条或多条重复的数据
            JSONObject jsonObject2=null;
            for (int i1 = 0; i1 < array.size(); i1++) {
                jsonObject2 = (JSONObject)array.get(i1);
                if(i!=i1){
                    if(!jsonObject.getString("customerName").equals("重复值")){
                        if(jsonObject.equals(jsonObject2)){
                            array.set(i1,array.get(array.size()-1));
                            repetition.add("第"+(i+1)+"条与第"+(i1+1)+"条数据重复");
                        }
                    }
                }
            }
        }

        String Aname = "";
        String Bname = "";
        String repe = "";
        String phone = "";
        String source = "";
        String type = "";
        String da = "";
        String allResult="";
        if(cusName.size()==0 && cusNameList.size()==0 && repetition.size()==0 &&
                phoneList.size()==0 && sourceList.size()==0 && typeList.size()==0 && dateList.size()==0
        ){
            array.remove(array.size()-1);
            for (int i = 0; i < array.size(); i++) {
                jsonObject = (JSONObject)array.get(i);
                Customer customer1 = new Customer();
                customer1.setCustomerName(jsonObject.getString("customerName"));
                customer1.setCustomerAddress(jsonObject.getString("customerAddress"));
                customer1.setCustomerPhone(Long.parseLong(jsonObject.getString("customerPhone")));
                customer1.setCustomerDemand(jsonObject.getString("customerDemand"));
                customer1.setCustomerType(jsonObject.getString("customerType"));
                customer1.setCustomerProvince(jsonObject.getString("customerProvince"));
                customer1.setCustomerArea(jsonObject.getString("customerArea"));
                customer1.setCustomerSource(jsonObject.getString("customerSource"));
                customer1.setCustomerCity(jsonObject.getString("customerCity"));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date date = sdf.parse(jsonObject.getString("customerDate"));
                customer1.setCustomerDate(date);
                customer1.setCustomerDele("潜在客户");
                customerDao.save(customer1);
            }
            allResult="success";
        }else{
            for (int i = 0; i < cusName.size(); i++) {
                Aname+=cusName.get(i)+"、";
            }
            //去重
            HashSet a = new HashSet(cusNameList);
            cusNameList.clear();
            cusNameList.addAll(a);
            for (int i = 0; i < cusNameList.size(); i++) {
                 Bname+=cusNameList.get(i)+"、";
            }
            for (int i = 0; i < repetition.size(); i++) {
                repe+=repetition.get(i)+"、";
            }
            //去重
            HashSet b = new HashSet(phoneList);
            phoneList.clear();
            phoneList.addAll(b);
            for (int i = 0; i < phoneList.size(); i++) {
                phone+=phoneList.get(i)+"、";
            }
            for (int i = 0; i < sourceList.size(); i++) {
                source+=sourceList.get(i)+"、";
            }
            for (int i = 0; i < typeList.size(); i++) {
                type+=typeList.get(i)+"、";
            }
            //去重
            HashSet c = new HashSet(dateList);
            dateList.clear();
            dateList.addAll(c);
            for (int i = 0; i < dateList.size(); i++) {
                da+=dateList.get(i)+"、";
            }
        }
        map.put("Aname",Aname);
        map.put("Bname",Bname);
        map.put("repetition",repe);
        map.put("phone",phone);
        map.put("source",source);
        map.put("type",type);
        map.put("date",da);
        map.put("allResult",allResult);
        return map;
    }
     //统计客户
     public List<Shuliang> selectcustomer(){
         System.out.println(customerMapper.selectcustomer());
         return customerMapper.selectcustomer();
     }

}
